﻿using System;
using System.Linq;
using System.Web.Mvc;
using Actya.Core.Infrastructure;
using Actya.Core.SiteStructure;

namespace Actya.Web.ModelBinders
{
	public class WidgetModelBinder : DefaultModelBinder
	{
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			var widgetTypeName = controllerContext.HttpContext.Request.Form["Widget.WidgetTypeName"];
			if (!String.IsNullOrEmpty(widgetTypeName))
			{
				// DIRTY: because the model binder runs BEFORE OnActionExecuting of the CmsContext filter we can't use ICmsContext
				// here to access the current site.
				var host = DependencyResolver.Current.GetService<ICmsHost>();
				var site = DependencyResolver.Current.GetService<ISiteService>().FindSiteByHostUrl(host.Settings.HostUrl);
				var widgetType = site.WidgetTypes.SingleOrDefault(wt => wt.Name == widgetTypeName);
				if (widgetType != null)
				{
					var widgetModelType = Type.GetType(widgetType.WidgetModelType);
					if (widgetModelType != null)
					{
						var item = Activator.CreateInstance(widgetModelType);

						var newBindingContext = new ModelBindingContext(bindingContext);
						newBindingContext.ModelName = bindingContext.ModelName;

						Func<object> modelAccessor = () => item;
						newBindingContext.ModelMetadata = new ModelMetadata(new DataAnnotationsModelMetadataProvider(),
						                                                    bindingContext.ModelMetadata.ContainerType, modelAccessor, item.GetType(), bindingContext.ModelName);

						return base.BindModel(controllerContext, newBindingContext);
					}
				}
			}
			return base.BindModel(controllerContext, bindingContext);
		}
	}
}